<?php
/*
Plugin Name: msdn-magazine
Plugin URI: http://www.hengha.info
Description: Crawl blog from http://msdn.microsoft.com/zh-cn/magazine/ee310108.aspx
Version: 1.0
Author: tomcat
Author URI: http://www.hengha.info
Text Domain: msdn-magazine
Domain Path: /languages/
*/

function msdn_magazine_add_small_interval($schedules)
{
    if (!isset($schedules['ten-minutes'])) {
        $schedules['ten-minutes'] = array(
            'interval' => 600,
            'display' => __('Ten Minutes', 'cnblogs')
        );
    }
    /*
    if (!isset($schedules['three-minutes'])) {
        $schedules['three-minutes'] = array(
            'interval' => 180,
            'display' => __('Three Minutes', 'cnblogs')
        );
    }
    */

    return $schedules;
}

add_filter('cron_schedules', 'msdn_magazine_add_small_interval');

/*
function load_plugin_textdomain() {
  load_plugin_textdomain( 'qiushibaike', FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );
}

add_action( 'plugins_loaded', 'load_plugin_textdomain' );
 */

function msdn_magazine_prefix_activation()
{
    wp_schedule_event(time(), 'ten-minutes', 'msdn_magazine_ten_minutes_event_hook');
    //wp_schedule_event(time(), 'three-minutes', 'msdn_magazine_three_minutes_event_hook');
    wp_schedule_event(time(), 'hourly', 'msdn_magazine_hourly_event_hook');
}

register_activation_hook(__FILE__, 'msdn_magazine_prefix_activation');

function msdn_magazine_get_anonymous_user_id()
{
    $userId = username_exists('unkown');
    if ($userId == null) {
        $userId = wp_insert_user(array(
            'user_login' => 'msdn-magazine',
            'user_email' => 'msdn-magazine@hengha.info',
            'nickname' => 'MSDN杂志',
            'display_name' => 'MSDN杂志',
            'user_pass' => wp_generate_password(20),
            'role' => 'subscriber'
        ));
    }
    return $userId;
}

function msdn_magazine_get_user_id($user)
{
    if ($user) {
        $userId = username_exists($user->authoruid);
        if ($userId == null) {
            $userId = wp_insert_user(array(
                'nickname' => $user->authorname,
                'display_name' => $user->authorname,
                'user_login' => $user->authoruid,
                'user_email' => $user->authoruid . '@oschina.net',
                'user_pass' => wp_generate_password(20),
                'role' => 'subscriber'
            ));
            update_user_meta($userId, 'item_id', $user->authoruid);
        }
        return $userId;
    } else {
        return get_anonymous_user_id();
    }
}

function msdn_magazine_handle_blog_list($xml)
{
    $args = array(
        'post_type' => 'post',
        'post_status' => 'any',
        'meta_key' => 'item-id',
        'posts_per_page' => 1
    );

    $cat_id = get_cat_ID('MSDN杂志');
    $year = '2014';
    $year_cat_id = wp_create_category($year,$cat_id);



    foreach ($xml->xpath('/oschina/blogs/blog') as $item) {
        $model = new stdClass();

        foreach ($item as $child) {
            $model->{$child->getName()} = strval($child);
        }


        $userId = msdn_magazine_get_user_id($model);
        $args['meta_value'] = $model->id;
        $the_post = get_posts($args);
        if (!$the_post) {
            $tags = array('开源中国');
            $postId = wp_insert_post(array(
                'post_title' => $model->title,
                'post_content' => '',
                'post_name' => 'oschina-' . $model->id,
                'post_status' => 'draft',
                'post_author' => $userId,
                'post_type' => 'post',
                'post_category' => array($categoryId),
                'tags_input' => implode(',', $tags)
            ));

            update_post_meta($postId, 'published_at', $model->pubDate);
            update_post_meta($postId, 'url', $model->url);
            update_post_meta($postId, 'item-id', $model->id);
        }
    }
}

function msdn_magazine_get_blog_list()
{
    $args = array('user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
        'httpversion' => '1.1',
        'timeout' => 120);
    $content = wp_remote_get('http://msdn.microsoft.com/zh-cn/magazine/dn519915.aspx', $args);
    if (is_wp_error($content)) {
        error_log(sprintf("request oschina failed"));
        return;
    }
    $cat_id = get_cat_ID('MSDN杂志');
    $year = '2014';
    $year_cat_id = wp_create_category($year,$cat_id);

}

function msdn_magazine_get_blog_content()
{
    $categoryId = get_cat_ID('开源中国');
    $args = array(
        'post_type' => 'post',
        'post_status' => 'draft',
        'cat' => $categoryId,
        'posts_per_page' => 1,
        'orderby' => 'ID',
        'order' => 'ASC',
        'page' => 1
    );
    $the_post = get_posts($args);
    $rargs = array('user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
        'httpversion' => '1.1',
        'timeout' => 120);
    foreach ($the_post as $item) {
        $item_id = get_post_meta($item->ID, 'item-id', true);
        $content = wp_remote_get('http://www.oschina.net/action/api/blog_detail/?id=' . $item_id, $rargs);
        if (is_wp_error($content)) {
            error_log(sprintf("request oschina failed"));
            return;
        }
        $xml = simplexml_load_string($content['body']);
        foreach ($xml->xpath('/oschina/blog') as $blog) {
            $model = new stdClass();

            foreach ($blog as $child) {
                $model->{$child->getName()} = strval($child);
            }
            wp_update_post(
                array(
                    'ID' => $item->ID,
                    'post_content' => $model->body,
                    'tags_input' => '开源中国,' . $model->where
                )
            );
            wp_publish_post($item->ID);
        }
    }
}

add_action('msdn_magazine_hourly_event_hook', 'msdn_magazine_get_blog_list');
add_action('msdn_magazine_ten_minutes_event_hook', 'msdn_magazine_get_blog_content');
function msdn_magazine_prefix_deactivation()
{
    wp_clear_scheduled_hook('msdn_magazine_ten_minutes_event_hook');
    //wp_clear_scheduled_hook('msdn_magazine_three_minutes_event_hook');
    wp_clear_scheduled_hook('msdn_magazine_hourly_event_hook');
}

register_deactivation_hook(__FILE__, 'msdn_magazine_prefix_deactivation');
?>
